#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
项目服务层
处理项目管理相关的业务逻辑
"""

from typing import Dict, List, Optional, Any
from datetime import datetime
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import func, or_
from models import Project


class ProjectService:
    """项目服务类"""
    
    def __init__(self, db_session: Session):
        self.db_session = db_session
    
    def create_project(self, project_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        创建项目
        
        Args:
            project_data: 项目数据
            
        Returns:
            创建结果
        """
        try:
            # 验证必填字段
            required_fields = ['name', 'created_by']
            for field in required_fields:
                if not project_data.get(field):
                    return {
                        'success': False,
                        'message': f'Missing required field: {field}',
                        'project_id': None
                    }
            
            # 检查项目名是否已存在
            existing_project = self.db_session.query(Project).filter(
                Project.name == project_data.get('name')
            ).first()
            
            if existing_project:
                return {
                    'success': False,
                    'message': 'Project name already exists',
                    'project_id': None
                }
            
            # 创建项目数据
            new_project = Project(
                name=project_data.get('name'),
                description=project_data.get('description', ''),
                created_by=project_data.get('created_by'),
                status=project_data.get('status', 'active'),
                tags=project_data.get('tags', []),
                settings=project_data.get('settings', {})
            )
            
            self.db_session.add(new_project)
            self.db_session.commit()
            
            return {
                'success': True,
                'message': 'Project created successfully',
                'project_id': str(new_project.id)
            }
            
        except SQLAlchemyError as e:
            self.db_session.rollback()
            return {
                'success': False,
                'message': f'Error creating project: {str(e)}',
                'project_id': None
            }
    
    def get_all_projects(self, user_id: Optional[str] = None) -> Dict[str, Any]:
        """
        获取所有项目
        
        Args:
            user_id: 用户ID，如果提供则只返回该用户的项目
            
        Returns:
            项目列表
        """
        try:
            query = self.db_session.query(Project)
            
            if user_id:
                query = query.filter(Project.created_by == user_id)
            
            projects = query.order_by(Project.created_at.desc()).all()
            projects_data = [project.to_dict() for project in projects]
            
            return {
                'success': True,
                'projects': projects_data,
                'count': len(projects_data)
            }
            
        except SQLAlchemyError as e:
            return {
                'success': False,
                'message': f'Error fetching projects: {str(e)}',
                'projects': [],
                'count': 0
            }
    
    def get_projects(self, page: int = 1, per_page: int = 10, search: str = '') -> Dict[str, Any]:
        """
        分页获取项目
        
        Args:
            page: 页码
            per_page: 每页数量
            search: 搜索关键字
            
        Returns:
            分页项目数据
        """
        try:
            query = self.db_session.query(Project)
            
            # 搜索过滤
            if search:
                query = query.filter(
                    or_(
                        Project.name.contains(search),
                        Project.description.contains(search)
                    )
                )
            
            # 获取总数
            total = query.count()
            
            # 分页
            offset = (page - 1) * per_page
            projects = query.offset(offset).limit(per_page).order_by(Project.created_at.desc()).all()
            projects_data = [project.to_dict() for project in projects]
            
            return {
                'success': True,
                'projects': projects_data,
                'total': total
            }
            
        except SQLAlchemyError as e:
            return {
                'success': False,
                'message': f'Error fetching projects: {str(e)}',
                'projects': [],
                'total': 0
            }
    
    def get_project_by_id(self, project_id: str) -> Dict[str, Any]:
        """根据ID获取项目"""
        try:
            project = self.db_session.query(Project).filter(
                Project.id == int(project_id)
            ).first()
            
            if project:
                return {
                    'success': True,
                    'project': project.to_dict()
                }
            
            return {
                'success': False,
                'message': 'Project not found',
                'project': None
            }
            
        except (ValueError, SQLAlchemyError) as e:
            return {
                'success': False,
                'message': f'Error fetching project: {str(e)}',
                'project': None
            }
    
    def update_project(self, project_id: str, update_data: Dict[str, Any]) -> Dict[str, Any]:
        """更新项目"""
        try:
            project = self.db_session.query(Project).filter(
                Project.id == int(project_id)
            ).first()
            
            if not project:
                return {
                    'success': False,
                    'message': 'Project not found'
                }
            
            # 更新字段
            for key, value in update_data.items():
                if hasattr(project, key) and key != 'id':
                    setattr(project, key, value)
            
            project.updated_at = datetime.now()
            self.db_session.commit()
            
            return {
                'success': True,
                'message': 'Project updated successfully'
            }
            
        except (ValueError, SQLAlchemyError) as e:
            self.db_session.rollback()
            return {
                'success': False,
                'message': f'Error updating project: {str(e)}'
            }
    
    def delete_project(self, project_id: str) -> Dict[str, Any]:
        """删除项目"""
        try:
            project = self.db_session.query(Project).filter(
                Project.id == int(project_id)
            ).first()
            
            if not project:
                return {
                    'success': False,
                    'message': 'Project not found'
                }
            
            self.db_session.delete(project)
            self.db_session.commit()
            
            return {
                'success': True,
                'message': 'Project deleted successfully'
            }
            
        except (ValueError, SQLAlchemyError) as e:
            self.db_session.rollback()
            return {
                'success': False,
                'message': f'Error deleting project: {str(e)}'
            }
    
    def get_statistics(self) -> Dict[str, Any]:
        """获取项目统计信息"""
        try:
            total_projects = self.db_session.query(Project).count()
            active_projects = self.db_session.query(Project).filter(
                Project.status == 'active'
            ).count()
            
            # 按状态统计
            status_stats = self.db_session.query(
                Project.status,
                func.count(Project.id)
            ).group_by(Project.status).all()
            
            status_counts = {status: count for status, count in status_stats}
            
            return {
                'success': True,
                'statistics': {
                    'total_projects': total_projects,
                    'active_projects': active_projects,
                    'status_counts': status_counts
                }
            }
            
        except SQLAlchemyError as e:
            return {
                'success': False,
                'message': f'Error fetching statistics: {str(e)}',
                'statistics': {}
            }
    
    def get_all_projects(self, user_id: Optional[str] = None) -> Dict[str, Any]:
        """
        获取所有项目
        
        Args:
            user_id: 用户ID，如果提供则只返回该用户的项目
            
        Returns:
            项目列表
        """
        try:
            query = {}
            if user_id:
                query['created_by'] = user_id
                
            projects = list(self.projects_collection.find(query).sort('updated_at', -1))
            
            return {
                'success': True,
                'projects': projects,
                'count': len(projects)
            }
            
        except Exception as e:
            return {
                'success': False,
                'message': f'Error fetching projects: {str(e)}',
                'projects': [],
                'count': 0
            }
    
    def get_project_by_id(self, project_id: str) -> Dict[str, Any]:
        """根据ID获取项目详情"""
        try:
            from bson import ObjectId
            project = self.projects_collection.find_one({'_id': ObjectId(project_id)})
            
            if project:
                return {
                    'success': True,
                    'project': project
                }
            
            return {
                'success': False,
                'message': 'Project not found',
                'project': None
            }
            
        except Exception as e:
            return {
                'success': False,
                'message': f'Error fetching project: {str(e)}',
                'project': None
            }
    
    def update_project(self, project_id: str, update_data: Dict[str, Any]) -> Dict[str, Any]:
        """更新项目"""
        try:
            from bson import ObjectId
            
            # 添加更新时间
            update_data['updated_at'] = datetime.now()
            
            result = self.projects_collection.update_one(
                {'_id': ObjectId(project_id)},
                {'$set': update_data}
            )
            
            if result.matched_count > 0:
                return {
                    'success': True,
                    'message': 'Project updated successfully'
                }
            
            return {
                'success': False,
                'message': 'Project not found'
            }
            
        except Exception as e:
            return {
                'success': False,
                'message': f'Error updating project: {str(e)}'
            }
    
    def delete_project(self, project_id: str) -> Dict[str, Any]:
        """删除项目"""
        try:
            from bson import ObjectId
            
            result = self.projects_collection.delete_one({'_id': ObjectId(project_id)})
            
            if result.deleted_count > 0:
                return {
                    'success': True,
                    'message': 'Project deleted successfully'
                }
            
            return {
                'success': False,
                'message': 'Project not found'
            }
            
        except Exception as e:
            return {
                'success': False,
                'message': f'Error deleting project: {str(e)}'
            }
    
    def get_project_statistics(self) -> Dict[str, Any]:
        """获取项目统计信息"""
        try:
            # 总项目数
            total_projects = self.projects_collection.count_documents({})
            
            # 活跃项目数
            active_projects = self.projects_collection.count_documents({'status': 'active'})
            
            # 按状态分组
            pipeline = [
                {'$group': {'_id': '$status', 'count': {'$sum': 1}}}
            ]
            status_stats = list(self.projects_collection.aggregate(pipeline))
            
            # 最近创建的项目
            recent_projects = list(
                self.projects_collection.find({}, {'name': 1, 'created_at': 1})
                .sort('created_at', -1)
                .limit(5)
            )
            
            return {
                'success': True,
                'statistics': {
                    'total_projects': total_projects,
                    'active_projects': active_projects,
                    'status_distribution': status_stats,
                    'recent_projects': recent_projects
                }
            }
            
        except Exception as e:
            return {
                'success': False,
                'message': f'Error getting statistics: {str(e)}',
                'statistics': {}
            }